<?php

namespace app\common\model;

use fast\Http;
use think\Model;

class Login
{
    //重组条件返回
    public function recomResult($LoginResult)
    {
        $device  = $LoginResult['device'];
        $msg     = '';
        $resData = [];
        switch ($device) {
            case 'miniapp':
                if (config('site.getMobile')) {
                    $accessToken = accessToken($LoginResult['appId'], $LoginResult['appSercet']);
                    if (!$accessToken) $msg = 'AccessToken获取失败,请稍后重试';
                    $getMobileUrl    = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$accessToken";
                    $getMobileResult = Http::post($getMobileUrl, json_encode(['code' => $LoginResult['miniAppLoginMobileCode']]), ['msg' => '获取accessToken']);
                    $getMobileResult = json_decode($getMobileResult, true);
                    if (!isset($getMobileResult['errcode'])) {
                        $msg = $getMobileResult['errmsg'];
                    } else {
                        if ($getMobileResult['errcode'] != 'ok') {
                            $msg = $getMobileResult['errmsg'];
                        } else {
                            if (!$getMobileResult['phone_info']['phoneNumber']) {
                                $msg = '微信请求手机号码失败,请稍后重试';
                            } else {
                                $resData['mobile'] = $getMobileResult['phone_info']['phoneNumber'];
                            }
                        }
                    }
                }
                break;
            case 'mp':
                if (config('site.getUserInfo')) {
                    $mpOpenId    = $LoginResult['mpOpenId'];
                    $accessToken = accessToken($LoginResult['appId'], $LoginResult['appSercet']);
                    if (!$accessToken) $msg = 'AccessToken获取失败,请稍后重试';
                    $getLoginUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=$accessToken&openid=$mpOpenId&lang=zh_CN";
                    $getLoginUserInfo = Http::get($getLoginUserInfo, '', ['msg' => '公众号获取登录个人信息']);
                    $getLoginUserInfo = json_decode($getLoginUserInfo, true);
                    if (!isset($getLoginUserInfo['errcode']) || $getLoginUserInfo['errcode'] != 'ok') $msg = '微信请求用户信息失败,请稍后重试';
                    //$getLoginUserInfo内部存在数组,待完善
                    $resData['userInfo'] = $getLoginUserInfo;
                }
                break;
            case 'app':
            default:
                break;
        }
        return ['status' => 1, 'data' => $resData, 'msg' => $msg];
    }


    public function LoginInfo($param)
    {
        list($loginType, $appID, $appSercet, $loginCode, $mobileCode, $loginUrl, $superiorId, $loginTypeDevice, $inviteCode) =
            array($param['loginType'] ?? "", $param['appID'] ?? "",
                  $param['appSercet'] ?? "", $param['miniappLoginCode'] ?? $param['mpLoginCode'],
                  $param['miniappMobileCode'] ?? "", $param['loginUrl'] ?? "", $param['superiorId'] ?? "", $param['loginTypeDevice'] ?? "", $param['inviteCode'] ?? "");
        $miniAppOpenId = '';
        $mpOpenId      = '';
        $appOpenId     = '';
        if ($loginTypeDevice != 'app') {
            if (!$loginUrl) return ['status' => 0, 'data' => ['url' => $loginUrl], 'msg' => '登录地址为空,请尽快核查'];
            if (in_array($loginTypeDevice, ['miniapp', 'mp'])) {
                if ($loginTypeDevice == 'miniapp') $options['msg'] = '微信小程序登录';
                if ($loginTypeDevice == 'mp') $options['msg'] = '微信公众号登录';
                $LoginNoDecodeResult = Http::get($loginUrl, '', $options);
                $LoginResult         = json_decode($LoginNoDecodeResult, true);
                if (!isset($LoginResult['openid'])) return ['status' => 0, 'data' => ['LoginResult' => $LoginResult], 'msg' => $LoginResult['errmsg']];
                if (isset($LoginResult['unionid']) && !empty($LoginResult['unionid'])) $unionid = $LoginResult['unionid'];
                if ($loginTypeDevice == 'miniapp') $miniAppOpenId = $LoginResult['openid'];
                if ($loginTypeDevice == 'mp') $mpOpenId = $LoginResult['openid'];
            }
        } else {
            if (isset($param['unionid']) && !empty($param['unionid'])) $unionid = $param['unionid'];
            if (!$param['openId']) return ['status' => 0, 'data' => ['url' => $loginUrl], 'msg' => '未获取APP登录权限!'];
            $appOpenId = $param['openId'];
        }
        $LoginResultData = [
            'unionid'                => $unionid ?? '',
            'appOpenId'              => $appOpenId,
            'mpOpenId'               => $mpOpenId,
            'miniAppOpenId'          => $miniAppOpenId,
            'device'                 => $loginTypeDevice,
            'appId'                  => $appID,
            'appSercet'              => $appSercet,
            'miniAppLoginMobileCode' => $mobileCode,
            'mobile'                 => '',
            'userName'               => '',
            'sex'                    => '',
            'avatar'                 => '',
        ];
        $userInfo        = [];
        $recomArr        = $this->recomResult($LoginResultData);
        if ($recomArr['msg']) return ['status' => 0, 'data' => '', 'msg' => $recomArr['msg']];
        if (isset($recomArr) && !empty($recomArr['data']['mobile'])) $LoginResultData['mobile'] = $recomArr['data']['mobile'];
        if (isset($recomArr['data']['userInfo']) && !empty($recomArr['data']['userInfo'])) {
            $LoginResultData['userName'] = $recomArr['data']['userInfo']['nickname'];
            $LoginResultData['sex']      = $recomArr['data']['userInfo']['sex'];
            $LoginResultData['avatar']   = wxAvatarRemoveUrl($recomArr['data']['userInfo']['headimgurl']);
        }
        if ($inviteCode) {
            $superiorInfo = User::where('invite_code', $inviteCode)->field('id')->find();
            if (empty($superiorInfo)) return ['status' => 0, 'data' => ['invite_code' => $inviteCode], 'msg' => '邀请码失效'];
        }
        return ['status' => 1, 'data' => $LoginResultData, 'msg' => ''];
    }
}